﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace LdCms.BLL.Service
{
    using LdCms.EF.DbModels;
    
    using LdCms.EF.DbStoredProcedure;
    using LdCms.IBLL.Service;
    using LdCms.IDAL.Service;
    using LdCms.Common.Json;
    using LdCms.Common.Security;
    using LdCms.Common.Extension;
    using LdCms.Common.Utility;
    using LdCms.Common.Logs;

    /// <summary>
    /// 
    /// </summary>
    public partial class CommentService:BaseService<Ld_Service_Comment>,ICommentService
    {
        private readonly ICommentDAL CommentDAL;
        
        public CommentService(ICommentDAL CommentDAL)
        {
            
            this.CommentDAL = CommentDAL;
            this.Dal = CommentDAL;
        }
        public override void SetDal()
        {
            Dal = CommentDAL;
        }

        public bool SaveComment(Ld_Service_Comment entity)
        {
            try
            {
                int systemId = entity.SystemID;
                string companyId = entity.CompanyID;
                string commentId = entity.CommentID;
                string orderId = entity.OrderID;
                if (string.IsNullOrEmpty(commentId))
                {
                    var primarykey = PrimaryKeyHelper.PrimaryKeyType.ServiceComment;
                    var primaryKeyLen = PrimaryKeyHelper.PrimaryKeyLen.V2;
                    commentId = PrimaryKeyHelper.MakePrimaryKey(primarykey, primaryKeyLen);
                }
                entity.CommentID = commentId;
                entity.ServiceStatus = entity.ServiceStatus.ToInt();
                entity.ServicePoints = entity.ServicePoints.ToInt();
                entity.UpNum = entity.UpNum.ToInt();
                entity.DownNum = entity.DownNum.ToInt();
                entity.State = entity.State.ToBool();
                entity.CreateDate = DateTime.Now;

                var expression = ExtLinq.True<Ld_Service_Comment>().And(m => m.SystemID == systemId && m.CompanyID == companyId && m.OrderID == orderId);
                if (IsExists(expression))
                    throw new Exception("您已经评价过了！");

                int intnum = 0;
                var dbContext = new DAL.BaseDAL();
                var db = dbContext.DbEntities();
                using (var trans = db.Database.BeginTransaction())
                {
                    try
                    {
                        dbContext.Add(entity);
                        var orderExpression = ExtLinq.True<Ld_Sell_Order>().And(m => m.SystemID == systemId && m.CompanyID == companyId && m.OrderID == orderId);
                        var order = dbContext.Find(orderExpression);
                        if (order == null)
                            throw new Exception("order id invalid！");
                        order.CommentState = true;
                        order.CommentTime = DateTime.Now;
                        dbContext.Update(order);
                        intnum = db.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogsManager.LogPath = string.Empty;
                        LogsManager.logFielPrefix = string.Empty;
                        LogsManager.WriteLog(LogsFile.Error, string.Format("[{0}]-OrderInvoiceService", ex.HelpLink));
                        LogsManager.WriteLog(LogsFile.Error, string.Format("[{0}]-异常：{1}", ex.HelpLink, ex.Message));
                        LogsManager.WriteLog(LogsFile.Error, string.Format("[{0}]-OrderInvoiceService", ex.HelpLink));
                        trans.Rollback();
                    }
                    return intnum > 0;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public bool DeleteComment(int systemId, string companyId, string commentId)
        {
            try
            {
                var expression = ExtLinq.True<Ld_Service_CommentAppend>().And(m => m.SystemID == systemId && m.CompanyID == companyId && m.CommentID == commentId);
                var entity = GetComment(systemId, companyId, commentId);
                if (entity == null)
                    throw new Exception("comment id invalid！");

                int intnum = 0;
                var dbContext = new DAL.BaseDAL();
                var db = dbContext.DbEntities();
                using (var trans = db.Database.BeginTransaction())
                {
                    try
                    {
                        dbContext.Delete(expression);
                        dbContext.Delete(entity);
                        intnum = db.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogsManager.LogPath = string.Empty;
                        LogsManager.logFielPrefix = string.Empty;
                        LogsManager.WriteLog(LogsFile.Error, string.Format("[{0}]-CommentService", ex.HelpLink));
                        LogsManager.WriteLog(LogsFile.Error, string.Format("[{0}]-方法：DeleteComment", ex.HelpLink));
                        LogsManager.WriteLog(LogsFile.Error, string.Format("[{0}]-异常：{1}", ex.HelpLink, ex.Message));
                        LogsManager.WriteLog(LogsFile.Error, string.Format("[{0}]-CommentService", ex.HelpLink));
                        trans.Rollback();
                        throw new Exception(ex.Message);
                    }
                    return intnum > 0;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public Ld_Service_Comment GetComment(int systemId, string companyId, string commentId)
        {
            try
            {
                return Find(m => m.SystemID == systemId && m.CompanyID == companyId && m.CommentID == commentId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public Ld_Service_Comment GetCommentByOrderId(int systemId, string companyId, string orderId)
        {
            try
            {
                return Find(m => m.SystemID == systemId && m.CompanyID == companyId && m.OrderID == orderId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public List<Ld_Service_Comment> GetCommentTop(int systemId, string companyId, int count)
        {
            try
            {
                int total = Utility.ToTopTotal(count);
                var expression = ExtLinq.True<Ld_Service_Comment>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId);
                return FindListTop(expression, m => m.CreateDate, false, total).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Service_Comment> GetCommentPaging(int systemId, string companyId, int pageId, int pageSize)
        {
            try
            {
                var expression = ExtLinq.True<Ld_Service_Comment>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId);
                int pageIndex = Utility.ToPageIndex(pageId);
                int pageCount = Utility.ToPageCount(pageSize);
                return FindListPaging(expression, m => m.CreateDate, false, pageIndex, pageCount).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Service_Comment> SearchComment(int systemId, string companyId, string startTime, string endTime, string status, string keyword, int count)
        {
            try
            {
                DateTime dateStartTime = Utility.ToStartTime(startTime);
                DateTime dateEndTime = Utility.ToEndTime(endTime);
                int intStatus = status.ToInt();
                int total = Utility.ToTopTotal(count);
                //条件
                var expression = ExtLinq.True<Ld_Service_Comment>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId
                && m.CreateDate.Value.Date >= dateStartTime.Date && m.CreateDate.Value.Date <= dateEndTime.Date
                && (string.IsNullOrEmpty(status) ? true : m.ServiceStatus.Value == intStatus)
                && (m.MemberID.Contains(keyword) || m.OrderID.Contains(keyword) || m.Description.Contains(keyword)));
                //执行
                return FindListTop(expression, m => m.CreateDate, false, total).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public List<Ld_Service_Comment> GetCommentPagingByMemberId(int systemId, string companyId, string memberId, int pageId, int pageSize)
        {
            try
            {
                var expression = ExtLinq.True<Ld_Service_Comment>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId && m.MemberID == memberId);
                int pageIndex = Utility.ToPageIndex(pageId);
                int pageCount = Utility.ToPageCount(pageSize);
                return FindListPaging(expression, m => m.CreateDate, false, pageIndex, pageCount).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public int CountComment(int systemId, string companyId)
        {
            try
            {
                return Count(m => m.SystemID == systemId && m.CompanyID == companyId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public int CountComment(int systemId, string companyId, string memberId)
        {
            try
            {
                return Count(m => m.SystemID == systemId && m.CompanyID == companyId && m.MemberID == memberId);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public int CountComment(int systemId, string companyId, string startTime, string endTime, string status, string keyword)
        {
            try
            {
                DateTime dateStartTime = Utility.ToStartTime(startTime);
                DateTime dateEndTime = Utility.ToEndTime(endTime);
                int intStatus = status.ToInt();
                //条件
                var expression = ExtLinq.True<Ld_Service_Comment>();
                expression = expression.And(m => m.SystemID == systemId && m.CompanyID == companyId
                && m.CreateDate.Value.Date >= dateStartTime.Date && m.CreateDate.Value.Date <= dateEndTime.Date
                && (string.IsNullOrEmpty(status) ? true : m.ServiceStatus.Value == intStatus)
                && (m.MemberID.Contains(keyword) || m.OrderID.Contains(keyword) || m.Description.Contains(keyword)));
                return Count(expression);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }



    }
}
